package com.yuan.fullstackback.config.interceptor;

import com.yuan.fullstackback.utils.JwtUtil;
import com.yuan.fullstackback.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 登录 token 拦截认证
 * 需要在WebMvcConfig中注册到框架中
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        try {
            Map<String, Object> stringObjectMap = JwtUtil.parseToken(request.getHeader("Authorization"));
            //获取请求的Token并存入ThreadLocal线程中（业务数据）
            ThreadLocalUtil.set(stringObjectMap);
            //认证成功，放行
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            //认证失败，状态码401
            return false;
        }
    }

    /**
     * 请求响应完毕的时候清除ThreadLocal中的数据
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
